package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.FaceFeature;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.FaceSimilar;
import com.arcsoft.face.enums.ErrorInfo;
import com.arcsoft.face.enums.ImageFormat;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.ruoyi.common.constant.StaticObj;
import com.ruoyi.system.service.FaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class FaceServiceImpl implements FaceService {

    @Override
    public byte[] faceFeature(byte[] image) {
        ImageInfo imageInfo = ImageFactory.getRGBData(image);
        FaceEngine faceEngine = null;
        //检测人脸集合
        List<FaceInfo> faceInfoList = CollUtil.newArrayList();
        try {
            faceEngine = StaticObj.FACE_ENGINE_POOL.borrowObject();
            byte[] imageData = imageInfo.getImageData();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            int code = faceEngine.detectFaces(imageData, width, height, ImageFormat.CP_PAF_BGR24, faceInfoList);
            log.debug("人脸检测状态码:" + code);
            if (code == ErrorInfo.MOK.getValue()) {
                //未检测到人脸直接返回数据
                if (!faceInfoList.isEmpty()) {
                    FaceInfo faceInfo = faceInfoList.get(0);
                    FaceFeature faceFeature = new FaceFeature();
                    faceEngine.extractFaceFeature(imageData, width, height, ImageFormat.CP_PAF_BGR24, faceInfo, faceFeature);
                    return faceFeature.getFeatureData();
                }
            }
        } catch (Exception e) {
            log.error("获取人脸引擎失败", e);
        } finally {
            StaticObj.FACE_ENGINE_POOL.returnObject(faceEngine);
        }
        return new byte[0];
    }

    @Override
    public float faceComparison(byte[] feature1, byte[] feature2) throws Exception {
        FaceEngine faceEngine = null;
        FaceFeature faceFeature = new FaceFeature(feature1);
        FaceFeature libFeature = new FaceFeature(feature2);
        FaceSimilar faceSimilar = new FaceSimilar();
        try {
            faceEngine = StaticObj.FACE_ENGINE_POOL.borrowObject();
            int code = faceEngine.compareFaceFeature(faceFeature, libFeature, faceSimilar);
            log.debug("人脸比对状态码:" + code);
            if (code == ErrorInfo.MOK.getValue()) {
                return faceSimilar.getScore();
            } else {
                throw new RuntimeException("人脸比对失败, code:" + code);
            }
        } catch (Exception e) {
            log.error("获取人脸引擎失败", e);
            throw e;
        } finally {
            StaticObj.FACE_ENGINE_POOL.returnObject(faceEngine);
        }
    }
}
